/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.grnt.buddy;

import java.util.Set;
import org.grnt.buddy.BuddiesTreeControler.BuddiesTravelor;
import org.grnt.common.Function;
import static org.grnt.buddy.BuddiesContext.*;

/**
 *
 * This class accomplished a foreword travel effect on buddies tree.
 * @author sayid
 */
public class BuddiesForewordTravel implements BuddiesTravelor{
	static final Buddies buddies = getBuddies();
	Long root = null;

	public boolean setRoot(Long root) {
		this.root = (buddies.containsKey(root)) ? root: null;
		return isActive();
	}

	public boolean isActive() {
		return this.root != null;
	}

	public void travel(Function<BuddyDecorator, ?> doElement) {
		if (! isActive()) return;
		BuddyDecorator buddyItem = buddies.get(root);
		doElement.doWith(buddyItem);
		travel(buddyItem.getChildren(), doElement);
	}

	private void travel(Set<Long> childrenIds, Function<BuddyDecorator, ?> doElement) {
		if (childrenIds == null) return;

		for(Long childId : childrenIds) {
			BuddyDecorator childItem = buddies.get(childId);
			doElement.doWith(childItem);
			if (childItem != null) travel(childItem.getChildren(), doElement);
		}
	}

}
